package com.aiyige.page.publish.guarantee;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.page.main.MainPage;
import com.aiyige.page.my.merchandisemanagement.model.TabItem;
import com.aiyige.page.publish.guarantee.adapter.GuaranteeAdapter;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.publish.guarantee.model.GuaranteeResp;
import com.aiyige.page.publish.learnvideo.model.PublishLearnVideoFormModel;
import com.aiyige.page.publish.majorcourse.model.MajorCourseFormModel;
import com.aiyige.page.publish.publishresult.PublishResult;
import com.aiyige.page.publish.traingcard.model.TraingCardFormModel;
import com.aiyige.page.publish.traingclass.model.TraingClassFormModel;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.SelectGuaranteePage)
public class SelectGuaranteePage extends AppCompatActivity {
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    Button titleActionBtn;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    GuaranteeAdapter guaranteeAdapter;
    @Autowired
    String subject;
    @Autowired
    MajorCourseFormModel majorCourseFormModel;
    @Autowired
    TraingClassFormModel traingClassFormModel;
    @Autowired
    TraingCardFormModel traingCardFormModel;
    @Autowired
    PublishLearnVideoFormModel learnVideoFormModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_guarantee);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (TextUtils.isEmpty(subject)) {
            subject = "";
        }
        if (majorCourseFormModel == null && traingClassFormModel == null && traingCardFormModel == null && learnVideoFormModel == null) {
            ToastX.show(R.string.unknown_error);
            return;
        }
        titleTv.setText(R.string.guarantee);
        titleActionBtn.setText(R.string.go_on);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        guaranteeAdapter = new GuaranteeAdapter();
        recyclerView.setAdapter(guaranteeAdapter);
        requestData();
    }

    public void requestData() {
        new RequestDataTask().execute();
    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                setResult(RESULT_CANCELED);
                finish();
                break;
            case R.id.titleActionBtn:
                if (majorCourseFormModel != null) {
                    int publishOperationType;
                    switch (majorCourseFormModel.getOperationType()) {
                        case PublishUtil.OPERATION_TYPE_COPY:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW;
                            break;
                        case PublishUtil.OPERATION_TYPE_EDIT:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW;
                            break;
                        default:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                            break;
                    }
                    majorCourseFormModel.setGuaranteeItemList(getSelectedItems());
                    new PublishMajorCourseTask().execute(publishOperationType, majorCourseFormModel);
                } else if (traingClassFormModel != null) {
                    int publishOperationType;
                    switch (traingClassFormModel.getOperationType()) {
                        case PublishUtil.OPERATION_TYPE_COPY:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW;
                            break;
                        case PublishUtil.OPERATION_TYPE_EDIT:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW;
                            break;
                        default:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                            break;
                    }
                    traingClassFormModel.setGuaranteeItemList(getSelectedItems());
                    new PublishTraingClassTask().execute(publishOperationType, traingClassFormModel);
                } else if (traingCardFormModel != null) {
                    int publishOperationType;
                    switch (traingCardFormModel.getOperationType()) {
                        case PublishUtil.OPERATION_TYPE_COPY:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW;
                            break;
                        case PublishUtil.OPERATION_TYPE_EDIT:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW;
                            break;
                        default:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                            break;
                    }
                    traingCardFormModel.setGuaranteeItemList(getSelectedItems());
                    new PublishTraingCardTask().execute(publishOperationType, traingCardFormModel);
                } else if (learnVideoFormModel != null) {
                    int publishOperationType;
                    switch (learnVideoFormModel.getOperationType()) {
                        case PublishUtil.OPERATION_TYPE_COPY:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_COPY_SUBMIT_REIVEW;
                            break;
                        case PublishUtil.OPERATION_TYPE_EDIT:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW;
                            break;
                        default:
                            publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                            break;
                    }
                    learnVideoFormModel.setSelectGuaranteeItemList(getSelectedItems());
                    new PublishLearnVideoTask().execute(publishOperationType, learnVideoFormModel);
                }
                break;
        }
    }

    public List<GuaranteeItem> getSelectedItems() {
        List<GuaranteeItem> selectedList = new LinkedList<>();
        List<GuaranteeItem> guaranteeItemList = guaranteeAdapter.getData();
        for (GuaranteeItem guaranteeItem : guaranteeItemList) {
            if (guaranteeItem.isSelected()) {
                selectedList.add(guaranteeItem);
            }
        }
        return selectedList;
    }

    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        List<GuaranteeItem> guaranteeItemList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectGuaranteePage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .getGuarantee(subject)
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                List<GuaranteeResp> guaranteeRespList = JSON.parseArray(json, GuaranteeResp.class);
                for (GuaranteeResp guaranteeResp : guaranteeRespList) {
                    guaranteeItemList.add(GuaranteeItem.newBuilder()
                            .id(guaranteeResp.getId())
                            .title(guaranteeResp.getName())
                            .content(guaranteeResp.getDetail())
                            .build());
                }
                resumeSelected();
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                guaranteeAdapter.setNewData(guaranteeItemList);
            }
        }

        public void resumeSelected() {
            List<GuaranteeItem> selectedList = new LinkedList<>();
            if (majorCourseFormModel != null) {
                if (!ListUtil.isEmpty(majorCourseFormModel.getGuaranteeItemList())) {
                    selectedList.addAll(majorCourseFormModel.getGuaranteeItemList());
                }
            } else if (traingClassFormModel != null) {
                if (!ListUtil.isEmpty(traingClassFormModel.getGuaranteeItemList())) {
                    selectedList.addAll(traingClassFormModel.getGuaranteeItemList());
                }
            } else if (traingCardFormModel != null) {
                if (!ListUtil.isEmpty(traingCardFormModel.getGuaranteeItemList())) {
                    selectedList.addAll(traingCardFormModel.getGuaranteeItemList());
                }
            } else if (learnVideoFormModel != null) {
                if (!ListUtil.isEmpty(learnVideoFormModel.getSelectGuaranteeItemList())) {
                    selectedList.addAll(learnVideoFormModel.getSelectGuaranteeItemList());
                }
            }
            outLoop:
            for (GuaranteeItem selectedItem : selectedList) {
                for (GuaranteeItem item : guaranteeItemList) {
                    try {
                        if (selectedItem.getId().equals(item.getId())) {
                            item.setSelected(true);
                            continue outLoop;
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    }

    public class PublishMajorCourseTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int publishOperationType;
        MajorCourseFormModel majorCourseFormModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectGuaranteePage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            publishOperationType = (int) objects[0];
            majorCourseFormModel = (MajorCourseFormModel) objects[1];
            try {
                return PublishUtil.publishMajorCourse(publishOperationType, majorCourseFormModel);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                finish();
                ToastX.show(R.string.publishing_course);
                PublishUtil.jumpToMMPage(SelectGuaranteePage.this);
            }

        }
    }

    public class PublishTraingClassTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int publishOperationType;
        TraingClassFormModel traingClassFormModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectGuaranteePage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            publishOperationType = (int) objects[0];
            traingClassFormModel = (TraingClassFormModel) objects[1];
            try {
                return PublishUtil.publishTraingClass(publishOperationType, traingClassFormModel);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                finish();
                PublishUtil.jumpToMMPage(SelectGuaranteePage.this);
            }

        }
    }

    public class PublishTraingCardTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        int publishOperationType;
        TraingCardFormModel traingCardFormModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectGuaranteePage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            publishOperationType = (int) objects[0];
            traingCardFormModel = (TraingCardFormModel) objects[1];
            try {
                return PublishUtil.publishTraingCard(publishOperationType, traingCardFormModel);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                finish();
                PublishUtil.jumpToMMPage(SelectGuaranteePage.this);
            }
        }
    }

    public class PublishLearnVideoTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        LearnVideoModel learnVideoModel;
        Integer publishOperationType;
        PublishLearnVideoFormModel formModel;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectGuaranteePage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                publishOperationType = (Integer) objects[0];
                formModel = (PublishLearnVideoFormModel) objects[1];
                learnVideoModel = PublishUtil.publishLearnVideo(publishOperationType, formModel);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                setResult(RESULT_OK);
                finish();
                ToastX.show(R.string.publishing_learn_video);
                PublishUtil.jumpToMMPage(SelectGuaranteePage.this);
            }
        }
    }
}
